package com.woshua.processor;

import com.woshua.handler.AnnotationHandler;
import com.woshua.handler.ViewInjectHandler;
import com.woshua.utils.FileUtils;
import com.woshua.writer.AdapterWriter;
import com.woshua.writer.DefaultAdapterWriter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;

/*
 * 注入视图的注解Processor
 * */
@SupportedAnnotationTypes("com.woshua.annotation.ViewInjector")
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class ViewInjectProcessor extends AbstractProcessor {

    /*
     * 注解处理器集合(需要多种处理器处理(视图，事件),视图注入可以有不同的处理方式)
     * */
    List<AnnotationHandler> mHandlers = new ArrayList<>();
    private Map<String, List<VariableElement>> map=new HashMap<>();
    private AdapterWriter writer;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
//        初始化注解处理器
        registerHandler(new ViewInjectHandler());
//        初始化辅助类生成器
        writer = new DefaultAdapterWriter(processingEnv);
    }

    protected void registerHandler(AnnotationHandler annotationHandler) {
        mHandlers.add(annotationHandler);
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        //测试是否能在编译器访问到java类
//        FileUtils.print("steven访问到了类成员");

        for (AnnotationHandler annotationHandler : mHandlers) {
            //关联环境
            annotationHandler.attachProcessingEnvironment(processingEnv);
//            处理注解(哪些类那些属性需要注入到列表)
            map = annotationHandler.handAnnotation(roundEnv);
        }

        //生成辅助类
        writer.generate(map);
        return true;
    }
}
